<template>
    <el-form>
        <el-form-item>
            <el-form-item class="mb5">
                <el-button type="primary" @click="onSave">
                    保存
                </el-button>
            </el-form-item>
        </el-form-item>
        <el-form-item>
            <el-tree
                ref="treeRef"
                class="allscreen"
                :data="treeData"
                :props="defaultProps"
                :highlight-current="true"
                empty-text="请给角色授权"
                :node-key="'id'"
                :expand-on-click-node="false"
                show-checkbox
                @node-click="onTreeClick"
                @check-change="onTreeCheckChange"
            >
            </el-tree>
        </el-form-item>
        <el-table ref="tableRef" :data="tableData" v-bind="tableDefaultAttribute" 
            :max-height="tableHeight">
            <template #empty>
                <span>无数据</span>
            </template>
            <el-table-column type="selection" width="55" align="center"/>
            <template v-for="col in tableColumns" :key="col.prop">
                <el-table-column v-if="!col.isHidden" :align="col.align" :prop="col.prop" :label="col.label"
                    :type="col.type" :sortable="col.sortable">

                </el-table-column>
            </template>            
            
        </el-table>        
    </el-form>
</template>
<script setup lang="ts" name="RoleFunc">
import { ref, reactive, onMounted, toRaw, nextTick, ComputedRef } from 'vue';
import { forEach } from 'lodash';
import { ElTable, ElTree, TreeNode } from 'element-plus';
// import { Document } from '@element-plus/icons-vue';
import { TableColumn, Tree } from '@/common/types/app';
import { Request } from '@/app/request';
import { ActionModel, MenuActionModel, MenuModel } from '@/common/types/model';
import { tableColumnDefault, tableDefaultAttribute, useTableInfo } from '@/hooks/useTable';
import { TreeNodeData } from 'element-plus/es/components/tree-v2/src/types';
import { tableMaxHeightAdjust } from '@/common/const';
type MenuNode = MenuModel & {$treeNodeId?: number};
const treeRef = ref<InstanceType<typeof ElTree>>();
const treeData = reactive<Tree[]>([]);
const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = reactive<Array<ActionModel>>([]);

const defaultProps = {
    children: 'children',
    label: 'label',
};
const tableColumns = reactive<TableColumn[]>(
[

    { ...tableColumnDefault, order: 1, prop: 'label', label: '功能名称', sortable: true },
    { ...tableColumnDefault, order: 2, prop: 'url', label: 'url', sortable: true },
    { ...tableColumnDefault, order: 3, prop: 'remark', label: '备注', sortable: false },
]
);
// let tableHeight: ComputedRef;
const props = defineProps<{
    roleId: number;
}>();
const emit = defineEmits(['yh-closedialog']);

const getActions = async (menuId: number) => {
    const req = new Request('角色菜单功能查询', {
        roleId: props.roleId,
        menuId: menuId,
    });
    
    const r = await req.post();
    if (r.code > 100) {
        tableData.length = 0;
        r.obj.forEach((element: ActionModel) => {
            tableData.push(element);
            if ((r.ext as number[]).indexOf(element.id as number) >= 0) {
                tableRef.value?.toggleRowSelection(element, true);
            }
        });
        
    }
}
const tableHeight = ref(100);
const onRefresh = async () => {
    const req = new Request('角色菜单Tree', {roleId: props.roleId});
    const r = await req.post();
    if (r.code > 100) {
        forEach(r.obj, (e) => {
            if (e['type'] === 'menu') {
                e['disabled'] = true;
            }
            treeData.push(e);
        });
        await nextTick();
        const checkedMenus: number[] = [];

        forEach(r.ext, (e) => {
            // treeRef.value?.setChecked(e, true, false);
            checkedMenus.push(e);
        });
       
        treeRef.value?.setCheckedKeys(checkedMenus, true);
    }
}
onMounted(async () => {
    onRefresh();
    tableHeight.value = window.innerHeight - Math.ceil(tableRef.value?.$el.getBoundingClientRect().bottom ) + tableMaxHeightAdjust;
});

const onTreeClick = async (_node: any, data: any) => {
    const node = _node ?? treeRef.value?.getCurrentNode();
    const treeNode = treeRef.value?.getNode(node.id);
    // console.log('node', node);
    // console.log('trrNode', treeRef.value?.getNode(node.id));
    
    if (data.data.type === 'menuitem') {
        // console.log('执行');
        await getActions(data['data']['id']);
        if (!treeNode?.checked) {
            tableRef.value?.clearSelection();    
        }
    } else {
        tableData.length = 0;
    }
}
const onTreeCheckChange = async (node: any, checked: boolean) => {
    
    if (checked) {
        /* tableRef.value?.clearSelection();
        tableRef.value?.toggleAllSelection() */
    } else {
        tableRef.value?.clearSelection();
    }
    treeRef.value?.setCurrentKey(node.id, false);
    treeRef.value?.$emit('node-click', null, {data: node});
    
}

const onSave = async () => {
   
    const selecteds = treeRef.value?.getCheckedNodes(false, true) as TreeNodeData[];
    const menus: number[] = [];
    selecteds.forEach(element => {
        menus.push(element.id);
    });
    
    
    const actions = Array<number>();
    tableRef.value?.getSelectionRows().forEach( (element: ActionModel) => {
        actions.push(element.id as number);
    });
   
    const req = new Request<any>('设置角色权限', {
        roleId: props.roleId,
        menuId: treeRef.value?.getCurrentKey() as number,
        menus,
        actions
    });
    const r = await req.post();
    if (r.code > 100) {
        emit('yh-closedialog');
    }
};

</script>
<style lang="scss" scoped>
.mb5 {
    margin-bottom: 10px;
}

.allscreen {
    width: 100%;
}
</style>
